package rabbitMQ.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("124.223.31.81");
        factory.setPort(5672);
        factory.setVirtualHost("bite");
        factory.setUsername("study");
        factory.setPassword("study");
        Connection connection = factory.newConnection();
        //创建Channel
        Channel channel = connection.createChannel();
        //声明一个队列Queue
        channel.queueDeclare("hello", true, false, false, null);
        //消费消息
        /*
        basicConsume(String queue, boolean autoAck, Consumer callback)
        参数:
        1. queue: 队列名称
        2. autoAck: 是否⾃动确认, 消费者收到消息之后,⾃动和MQ确认
        3. callback: 接受到消息后，执行的逻辑
        */
        DefaultConsumer consumer = new DefaultConsumer(channel){
            //从队列中收到消息，就会执行的内容
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到的消息：" + new String(body));

            }
        };
        channel.basicConsume("hello",  true, consumer);

        //等待程序执行完成
        Thread.sleep(3000);

        //释放资源
       /* channel.close();;
        connection.close();*/
    }
}
